<template>
  <div class="login">
    <div class="login_box">
      <div class="head_box">
        <img src="../assets/logo.png" alt="" />
      </div>
      <el-form ref="loginref" :rules="rules" :model="login" class="form" label-width="0">
        <el-form-item prop="username">
          <el-input prefix-icon="iconfont icon-denglu" v-model="login.username">
          </el-input>
        </el-form-item>
        <el-form-item prop="password">
          <el-input type="password" prefix-icon="iconfont icon-mima" v-model="login.password"></el-input>
        </el-form-item>
        <el-form-item class="btns">
          <el-button type="primary" @click="dl">登录</el-button>
          <el-button type="info" @click="cz">重置</el-button>
        </el-form-item>
      </el-form>
    </div>
  </div>
</template>

<script>
export default {
  data() {
    return {
      login: {
        username: "admin",
        password: "123456",
      },
      rules: {
        username: [
          { required: true, message: '请输入用户名', trigger: 'blur' },
          { min: 3, max: 10, message: '长度在 3 到 10 个字符', trigger: 'blur' }
        ],
        password: [
          { required: true, message: '请输入密码', trigger: 'blur' }
        ],
      }
    };
  },
  methods: {
    cz() {
      this.$refs.loginref.resetFields();
    },
    dl() {
      this.$refs.loginref.validate(async (v) => {
        if (!v) return
        //表单校验成功
        let { data: res } = await this.$http.post("login", this.login);
        if (res.meta.status !== 200) return this.$message.error(res.meta.msg);
        this.$message.success(res.meta.msg);
        //保存token到sessionStorage中
        sessionStorage.setItem('token', res.data.token);
        //路由跳转/home
        if (this.$route.query.redirect) {
          console.log(true);
          this.$router.push({ path: this.$route.query.redirect })
        } else {
          this.$router.push({ path: '/home' })
        }
      });
    }
  }
};
</script>

<style lang="scss" scoped>
.login {
  height: 100%;
  background-color: #2b4b6b;

  .login_box {
    width: 450px;
    height: 300px;
    background-color: #fff;
    border-radius: 3px;
    position: absolute;
    top: 50%;
    left: 50%;
    transform: translate(-50%, -50%);

    .head_box {
      width: 130px;
      height: 130px;
      border: 1px solid #eee;
      border-radius: 50%;
      position: absolute;
      left: 50%;
      transform: translate(-50%, -50%);
      background-color: #fff;
      box-shadow: 0 0 10px #ddd;
      padding: 10px;

      img {
        width: 100%;
        height: 100%;
        border-radius: 50%;
        background-color: #eee;
      }
    }
  }
}

//登录按钮往后对齐
.btns {
  display: flex;
  justify-content: flex-end;
  margin-right: 20px;
}

//整个表单从下往上排列
.form {
  position: absolute;
  bottom: 0;
  width: 100%;
  padding: 0 20px;
  box-sizing: border-box;
}
</style>
